/*
 * MAE功能测试程序
 * 用于验证FuzzyTrustApp中的MAE数据收集功能是否正常工作
 */

#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>

// 模拟MAE计算函数
double calculateMean(const std::vector<double>& values) {
    if (values.empty()) {
        return 0.0;
    }
    
    double sum = 0.0;
    for (double value : values) {
        sum += value;
    }
    return sum / values.size();
}

double calculateStdDev(const std::vector<double>& values, double mean) {
    if (values.size() <= 1) {
        return 0.0;
    }
    
    double variance = 0.0;
    for (double value : values) {
        variance += (value - mean) * (value - mean);
    }
    variance /= (values.size() - 1);
    
    return std::sqrt(variance);
}

// 模拟IT2-Sigmoid信任计算
double calculateIT2SigmoidTrust(const std::vector<double>& reputationVector) {
    if (reputationVector.size() != 7) {
        return 0.5;
    }
    
    // 简化的IT2-Sigmoid计算
    std::vector<double> weights = {0.15, 0.15, 0.15, 0.15, 0.1, 0.15, 0.15};
    double weightedScore = 0.0;
    
    for (size_t i = 0; i < reputationVector.size(); i++) {
        weightedScore += weights[i] * reputationVector[i];
    }
    
    // IT2-Sigmoid函数（简化版）
    double theta_lower = 0.4;
    double theta_upper = 0.6;
    double k = 5.0;
    
    double lower = 1.0 / (1.0 + std::exp(-k * (weightedScore - theta_lower)));
    double upper = 1.0 / (1.0 + std::exp(-k * (weightedScore - theta_upper)));
    
    return (lower + upper) / 2.0; // 简化的区间中心
}

// 模拟Type-1 Sigmoid信任计算
double calculateType1SigmoidTrust(const std::vector<double>& reputationVector) {
    if (reputationVector.size() != 7) {
        return 0.5;
    }
    
    std::vector<double> weights = {0.15, 0.15, 0.15, 0.15, 0.1, 0.15, 0.15};
    double weightedScore = 0.0;
    
    for (size_t i = 0; i < reputationVector.size(); i++) {
        weightedScore += weights[i] * reputationVector[i];
    }
    
    double theta = 0.5;
    double k = 5.0;
    return 1.0 / (1.0 + std::exp(-k * (weightedScore - theta)));
}

// 模拟固定阈值法
double calculateThresholdTrust(const std::vector<double>& reputationVector) {
    if (reputationVector.size() != 7) {
        return 0.5;
    }
    
    double avgReputation = 0.0;
    for (double rep : reputationVector) {
        avgReputation += rep;
    }
    avgReputation /= reputationVector.size();
    
    double threshold = 0.6;
    return (avgReputation >= threshold) ? 1.0 : 0.0;
}

// 模拟无防御基线
double calculateNoDefenseTrust(const std::vector<double>& reputationVector) {
    if (reputationVector.size() != 7) {
        return 0.5;
    }
    
    double sum = 0.0;
    for (double rep : reputationVector) {
        sum += rep;
    }
    return sum / reputationVector.size();
}

// 模拟真实信任值计算
double calculateGroundTruthTrust(bool isMalicious) {
    if (isMalicious) {
        return 0.1 + (static_cast<double>(rand()) / RAND_MAX) * 0.3; // 0.1-0.4
    } else {
        return 0.7 + (static_cast<double>(rand()) / RAND_MAX) * 0.3; // 0.7-1.0
    }
}

int main() {
    std::cout << "MAE功能测试开始..." << std::endl;
    
    // 测试1: 统计函数测试
    std::cout << "\n测试1: 统计函数测试" << std::endl;
    std::vector<double> testData = {0.1, 0.2, 0.3, 0.4, 0.5};
    double mean = calculateMean(testData);
    double stdDev = calculateStdDev(testData, mean);
    
    std::cout << "测试数据: [0.1, 0.2, 0.3, 0.4, 0.5]" << std::endl;
    std::cout << "平均值: " << mean << " (期望: 0.3)" << std::endl;
    std::cout << "标准差: " << stdDev << " (期望: ~0.158)" << std::endl;
    
    assert(std::abs(mean - 0.3) < 0.001);
    assert(std::abs(stdDev - 0.158113883) < 0.001);
    std::cout << "✓ 统计函数测试通过" << std::endl;
    
    // 测试2: 信任评估方法测试
    std::cout << "\n测试2: 信任评估方法测试" << std::endl;
    std::vector<double> normalReputation = {0.8, 0.7, 0.9, 0.8, 0.6, 0.7, 0.8}; // 正常节点
    std::vector<double> maliciousReputation = {0.3, 0.2, 0.4, 0.3, 0.1, 0.2, 0.3}; // 恶意节点
    
    std::cout << "正常节点信誉向量: [0.8, 0.7, 0.9, 0.8, 0.6, 0.7, 0.8]" << std::endl;
    double it2_normal = calculateIT2SigmoidTrust(normalReputation);
    double t1_normal = calculateType1SigmoidTrust(normalReputation);
    double threshold_normal = calculateThresholdTrust(normalReputation);
    double none_normal = calculateNoDefenseTrust(normalReputation);
    
    std::cout << "  IT2-Sigmoid: " << it2_normal << std::endl;
    std::cout << "  Type-1 Sigmoid: " << t1_normal << std::endl;
    std::cout << "  固定阈值法: " << threshold_normal << std::endl;
    std::cout << "  无防御基线: " << none_normal << std::endl;
    
    std::cout << "\n恶意节点信誉向量: [0.3, 0.2, 0.4, 0.3, 0.1, 0.2, 0.3]" << std::endl;
    double it2_malicious = calculateIT2SigmoidTrust(maliciousReputation);
    double t1_malicious = calculateType1SigmoidTrust(maliciousReputation);
    double threshold_malicious = calculateThresholdTrust(maliciousReputation);
    double none_malicious = calculateNoDefenseTrust(maliciousReputation);
    
    std::cout << "  IT2-Sigmoid: " << it2_malicious << std::endl;
    std::cout << "  Type-1 Sigmoid: " << t1_malicious << std::endl;
    std::cout << "  固定阈值法: " << threshold_malicious << std::endl;
    std::cout << "  无防御基线: " << none_malicious << std::endl;
    
    // 验证正常节点的信任值应该高于恶意节点
    assert(it2_normal > it2_malicious);
    assert(t1_normal > t1_malicious);
    assert(none_normal > none_malicious);
    std::cout << "✓ 信任评估方法测试通过" << std::endl;
    
    // 测试3: MAE计算测试
    std::cout << "\n测试3: MAE计算测试" << std::endl;
    
    // 模拟10个节点的MAE计算
    std::vector<double> mae_it2, mae_t1, mae_threshold, mae_none;
    
    srand(42); // 固定随机种子以获得可重复结果
    
    for (int i = 0; i < 10; i++) {
        bool isMalicious = (i < 3); // 前3个节点为恶意节点（30%比例）
        
        // 生成随机信誉向量
        std::vector<double> reputation(7);
        for (int j = 0; j < 7; j++) {
            if (isMalicious) {
                reputation[j] = 0.1 + (static_cast<double>(rand()) / RAND_MAX) * 0.4; // 0.1-0.5
            } else {
                reputation[j] = 0.6 + (static_cast<double>(rand()) / RAND_MAX) * 0.4; // 0.6-1.0
            }
        }
        
        // 计算各方法的信任值
        double it2_trust = calculateIT2SigmoidTrust(reputation);
        double t1_trust = calculateType1SigmoidTrust(reputation);
        double threshold_trust = calculateThresholdTrust(reputation);
        double none_trust = calculateNoDefenseTrust(reputation);
        
        // 计算真实信任值
        double ground_truth = calculateGroundTruthTrust(isMalicious);
        
        // 计算绝对误差
        mae_it2.push_back(std::abs(it2_trust - ground_truth));
        mae_t1.push_back(std::abs(t1_trust - ground_truth));
        mae_threshold.push_back(std::abs(threshold_trust - ground_truth));
        mae_none.push_back(std::abs(none_trust - ground_truth));
        
        std::cout << "节点" << i << " (" << (isMalicious ? "恶意" : "正常") << "): "
                  << "真实=" << ground_truth << ", "
                  << "IT2=" << it2_trust << ", "
                  << "T1=" << t1_trust << ", "
                  << "阈值=" << threshold_trust << ", "
                  << "无防御=" << none_trust << std::endl;
    }
    
    // 计算各方法的平均MAE
    double avg_mae_it2 = calculateMean(mae_it2);
    double avg_mae_t1 = calculateMean(mae_t1);
    double avg_mae_threshold = calculateMean(mae_threshold);
    double avg_mae_none = calculateMean(mae_none);
    
    std::cout << "\nMAE结果:" << std::endl;
    std::cout << "  IT2-Sigmoid MAE: " << avg_mae_it2 << std::endl;
    std::cout << "  Type-1 Sigmoid MAE: " << avg_mae_t1 << std::endl;
    std::cout << "  固定阈值法 MAE: " << avg_mae_threshold << std::endl;
    std::cout << "  无防御基线 MAE: " << avg_mae_none << std::endl;
    
    std::cout << "✓ MAE计算测试通过" << std::endl;
    
    // 测试4: 恶意节点判定测试
    std::cout << "\n测试4: 恶意节点判定测试" << std::endl;
    
    int totalNodes = 20;
    double maliciousRatio = 25.0; // 25%
    int maliciousCount = static_cast<int>(totalNodes * maliciousRatio / 100.0);
    
    std::cout << "总节点数: " << totalNodes << std::endl;
    std::cout << "恶意节点比例: " << maliciousRatio << "%" << std::endl;
    std::cout << "恶意节点数量: " << maliciousCount << std::endl;
    
    int actualMaliciousCount = 0;
    for (int i = 0; i < totalNodes; i++) {
        bool isMalicious = (i < maliciousCount);
        if (isMalicious) actualMaliciousCount++;
        
        if (i < 10) { // 只显示前10个节点
            std::cout << "节点" << i << ": " << (isMalicious ? "恶意" : "正常") << std::endl;
        }
    }
    
    assert(actualMaliciousCount == maliciousCount);
    std::cout << "实际恶意节点数量: " << actualMaliciousCount << std::endl;
    std::cout << "✓ 恶意节点判定测试通过" << std::endl;
    
    std::cout << "\n🎉 所有测试通过！MAE功能正常工作。" << std::endl;
    
    return 0;
}